package com.lee.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lee.entity.Point;
import com.lee.mapper.PointMapper;
import com.lee.service.PointService;
import com.lee.vo.OrderDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

/***
 * @description: point service impl
 * @author : 青石路
 * @date: 2021/11/13 16:48
 */
@Service
@Slf4j
public class PointServiceImpl extends ServiceImpl<PointMapper, Point> implements PointService {

    /**
     * 下单金额转积分规则
     */
    private static final BigDecimal AMOUNT_TO_POINT_RULE = BigDecimal.TEN;

    @Override
    public void add(OrderDTO order) {
        // 1、幂等校验，不仅仅只是简单的查一遍，需要保证同个订单只有一笔积分记录
        // 幂等不是本文的主角，就不作过深探讨，这里仅做一个简单的判断
        LambdaQueryChainWrapper<Point> pointQuery = this.lambdaQuery();
        pointQuery.eq(Point::getOrderNo, order.getOrderNo());
        List<Point> points = pointQuery.list();
        if (!CollectionUtils.isEmpty(points)) {
            log.error("订单 = {} 已处理过，不能重复处理", order.getOrderNo());
            return;
        }

        // 2、积分处理
        Point point = new Point();
        point.setOrderNo(order.getOrderNo());
        point.setUserId(order.getUserId());
        // 下单金额与积分转换规则，这里写死成 10 倍
        point.setPointNum(order.getOrderAmount().multiply(AMOUNT_TO_POINT_RULE));
        point.setNote(order.getNote());
        this.save(point);
    }
}
